package org.fuys.coder.domain.redemption.service.policy.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.fuys.coder.domain.redemption.model.req.RedemptionReq;
import org.fuys.coder.domain.redemption.model.vo.RedemptionResult;
import org.fuys.coder.domain.redemption.service.policy.AwardRedemptionStrategy;
import org.fuys.coder.infrastructure.dao.AwardMapper;
import org.fuys.coder.infrastructure.dao.AwardRedemptionMapper;
import org.fuys.coder.infrastructure.dao.UserMapper;
import org.fuys.coder.infrastructure.model.po.Award;
import org.fuys.coder.infrastructure.model.po.AwardRedemption;
import org.fuys.coder.infrastructure.model.po.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.redemption.service.policy.impl
 * @className: PointAwardRedemptionStrategy
 * @author: WangJing
 * @description: 积分奖品兑换策略
 * @date: 2024/8/28 9:20
 * @version: 1.0
 */

@Service("pointAwardRedemptionStrategy")
public class PointAwardRedemptionStrategy implements AwardRedemptionStrategy {

    @Resource
    private UserMapper userMapper;

    @Resource
    private AwardRedemptionMapper awardRedemptionMapper;

    @Resource
    private AwardMapper awardMapper;

    @Override
    @Transactional
    public RedemptionResult doRedemption(RedemptionReq req,AwardRedemption awardRedemption) {
        final Integer userId = req.getUserId();
        final User user = userMapper.selectOne(new LambdaQueryWrapper<User>().select(User::getPoints).eq(User::getId, userId));
        final Award award = awardMapper.selectOne(new LambdaQueryWrapper<Award>().select(Award::getAwardContent)
                .eq(Award::getId, awardRedemption.getAwardId()));
        user.setPoints(user.getPoints()+Integer.parseInt(award.getAwardContent()));
        user.setId(userId);
        userMapper.updateById(user);
        awardRedemptionMapper.delete(new LambdaQueryWrapper<AwardRedemption>()
                    .eq(AwardRedemption::getUserId, userId).eq(AwardRedemption::getRedemptionCode,req.getAwardCode()));
        return RedemptionResult.normal();
    }
}
